package com.example.rizhaoscienceandtechnologymuseum.Utils;

import android.content.Context;

import com.example.baselibrary.Base.BaseCustomer;
import com.example.baselibrary.Utils.GetDeviceId;
import com.example.baselibrary.Utils.SPUtils;

public class MachineID {

    private String DeviceId;

    public static MachineID machineid;

    private getMachineIdLietener machineIdLietener;

    public static MachineID getInstance(){
        if (machineid == null){
            return new MachineID();
        }
        return machineid;
    }

    public  void getMachineId(final Context context){
        ThreadManager.getThreadPool().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    DeviceId = GetDeviceId.getDeviceId(context);
                    //获取保存在sd中的 设备唯一标识符
                    String readDeviceID = GetDeviceId.readDeviceID(context);
                    //获取缓存在  sharepreference 里面的 设备唯一标识
                    String string = (String) SPUtils.get(context, BaseCustomer.DEVICEID, "");
                    //判断 app 内部是否已经缓存,  若已经缓存则使用app 缓存的 设备id
                    if (string != null && !string.equals("")) {
                        // 说明有保存，那么久将其放出去呗
                        if (readDeviceID.equals(string)) {
                            //缓存和文件地址一样，直接返回出去
                            DeviceId = readDeviceID;
                            machineIdLietener.getID(DeviceId);
                        }
                    } else {
                        DeviceId = GetDeviceId.getDeviceId(context);
                        GetDeviceId.saveDeviceID(DeviceId, context);
                        machineIdLietener.getID(DeviceId);
                    }

                    //最后再次更新app 的缓存
                    System.out.println("zyf :" + DeviceId);

                } catch (Exception e) {
                    DeviceId = "未获取到设备硬件码";
                    e.printStackTrace();
                }
            }
        });
    }

    public interface getMachineIdLietener{
        void getID(String id);
    }
    public void setGetMachineidListener(Context context, getMachineIdLietener getId){
        machineIdLietener = getId;
        getMachineId(context);
    }

}
